package com.hkfn.rfb;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hkfn.rfb.common.activity.BaseActivity;
import com.hkfn.rfb.common.utils.DialogUtils;
import com.hkfn.rfb.common.utils.ToastUtils;
import com.xh.common.thread.AsyncExecutor;

import java.util.ArrayList;
import java.util.List;

public class WelcomeActivity extends BaseActivity {

    private final static int REQUEST_REQUEST_CODE = 0;

    private int requestTime = 0;

    private Dialog permissionDialog;
    private final static int REQUEST_SETTING_WHAT = 123;

    /**
     * 需要向用户申请的权限列表
     */
    private static String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setImmerseLayout();
        setContentView(R.layout.a_welcome);

        initApp();
    }

    private void initApp() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            skipToNextPage();
        } else {
            checkPermissions();
        }
    }

    /**
     * 申请权限
     */
    public void checkPermissions() {
        try {
            if (requestTime > 2){
                finish();
            }
            requestTime++;
            List<String> permissionList = new ArrayList<>();
            for (String permission : permissions) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                    permissionList.add(permission);
                }
            }
            if (permissionList.size() > 0) {
                ActivityCompat.requestPermissions(this, permissionList.toArray(new String[]{}), REQUEST_REQUEST_CODE);
                return;
            }
            permissionNextTips();

        } catch (Throwable e) {
            Log.e("checkPermissions", "", e);
        }
    }

    public void permissionNextTips() {
        skipToNextPage();
    }

    private void skipToNextPage(){
        AsyncExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1500);
                     // 判断用户是否登录

                    Bundle bundle = new Bundle();
                    openActivity(MainActivity.class, bundle, 0);

                    WelcomeActivity.this.finish();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_REQUEST_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //Toast.makeText(this, "权限被拒绝： "+permissions[i], Toast.LENGTH_SHORT).show();

                        // 二次请求，表现为：以前请求过这个权限，但是用户拒接了
                        // 在二次请求的时候，会有一个“不再提示的”checkbox
                        // 因此这里需要给用户解释一下我们为什么需要这个权限，否则用户可能会永久不在激活这个申请
                        // 方便用户理解我们为什么需要这个权限
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                            setPermissionDialog();
                        }
                        // 到这里就表示已经是第3+次请求，而且此时用户已经永久拒绝了，这个时候，我们引导用户到应用权限页面，让用户自己手动打开
                        else {
                            Toast.makeText(this, "部分权限被拒绝获取，将会会影响后续功能的使用，建议重新打开", Toast.LENGTH_LONG).show();
                            openAppPermissionSetting(REQUEST_SETTING_WHAT);
                        }
                        return;
                    }
                }

                // 到这里就表示用户允许了本次请求，我们继续检查是否还有待申请的权限没有申请
                if (isAllRequestedPermissionGranted()) {
                    permissionNextTips();
                } else {
                    checkPermissions();
                }
                break;
        }
    }

    public  void setPermissionDialog() {
        View.OnClickListener cancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissionDialog.dismiss();
                ToastUtils.showToast(WelcomeActivity.this, "权限尚未开启，无法使用消管平台");
                WelcomeActivity.this.finish();
            }
        };

        View.OnClickListener sureClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissionDialog.dismiss();
                checkPermissions();
            }
        };

        permissionDialog = DialogUtils.createPermissionTip(this, "您需要同意授权才能正常访问App", "权限申请", "取消", "去设置",
                cancelClickListener, sureClickListener);
        permissionDialog.show();
    }

    public  boolean isAllRequestedPermissionGranted() {
        for (final String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                return false;
            }
        }
        return true;
    }

    public boolean openAppPermissionSetting(int requestCode) {
        try {
            Intent intent =
                    new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + this.getPackageName()));
            intent.addCategory(Intent.CATEGORY_DEFAULT);

            // Android L 之后Activity的启动模式发生了一些变化
            // 如果用了下面的 Intent.FLAG_ACTIVITY_NEW_TASK ，并且是 startActivityForResult
            // 那么会在打开新的activity的时候就会立即回调 onActivityResult
            // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivityForResult(intent, requestCode);
            return true;
        } catch (Throwable e) {
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_SETTING_WHAT:
                if (isAllRequestedPermissionGranted()) {
                    permissionNextTips();
                } else {
                    Toast.makeText(this, "部分权限被拒绝获取，退出", Toast.LENGTH_LONG).show();
                    this.finish();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 取消返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) {
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(permissionDialog);
    }
}
